package com.analyse.stock.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.enums.StrategyEnum;
import com.analyse.stock.form.PickStockQueryForm;
import com.analyse.stock.model.StockAnalyseFocusModel;
import com.analyse.stock.service.IStockAnalyseFocus;
import com.analyse.stock.strategy.StrategyHandle;
import com.analyse.stock.utils.PublicHolidayUtil;
import com.analyse.stock.utils.StockStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 每日实盘操作,打排行榜的龙头股票
 * 每日早上 9：15 开始执行 ~ 9：30
 */
@Component
@Slf4j
public class AutoTopRankTradingJob implements Job {

    @Autowired
    private StrategyHandle strategyHandle;

    @Autowired
    private IStockAnalyseFocus stockAnalyseFocus;

    @Override
    public void execute(JobExecutionContext context) {
        Date now = new Date();
        boolean isTrading = PublicHolidayUtil.isTradingDateTime("XSHE",now, StockStringUtil.topRankTradingTimeFun);
        log.info("### 早盘集合竞价【打榜股票】,当前时间：{} , 【{}】早盘集合竞价时间 ###",
                DateUtil.format(now, DatePattern.NORM_TIME_PATTERN),isTrading?"正在":"不在");
        if(!isTrading){
            return;
        }
        StockAnalyseFocusModel queryModel = StockAnalyseFocusModel.me(0,
                DateUtil.offsetDay(DateUtil.date(),-1), BigDecimal.valueOf(200), StrategyEnum.TOP_RANK_TRADING,BigDecimal.valueOf(80));
        List<StockAnalyseFocusModel> focusList = stockAnalyseFocus.getFocusList(queryModel);
        if(CollUtil.isEmpty(focusList)){
            log.info("###  早盘集合竞价 在【股票池】中未发现需要关注打榜股票，今日不进行操作....");
            return;
        }
        String codes = focusList.stream()
                .map(StockAnalyseFocusModel::getStockCode).collect(Collectors.joining(StrUtil.COMMA));
        long time0 = System.currentTimeMillis();
        log.info("###  开始 早盘集合竞价 【打榜股票】{}....",codes);
        //一个股票开一个线程
        for(StockAnalyseFocusModel focusModel : focusList){
            PickStockQueryForm queryForm = new PickStockQueryForm();
            queryForm.setStockCode(focusModel.getStockCode());
            ThreadUtil.execAsync(() ->
                    strategyHandle.getStrategy(focusModel.getStrategyCode()).run(JSONObject.toJSONString(queryForm)),
                    true);
        }
        log.info("###  结束【打榜股票】,耗时：{}....",(System.currentTimeMillis()-time0));
    }
}
